package com.odl.ds.utils;


import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Antoneo on 2018/5/15 0015.
 * email: 782657190@qq.com
 */
@Slf4j
public class FileUtils {
    String newline = "\r\n";//windows

    /**
     * 写入文件,末尾自动添加\r\n  替换
     * @param file
     * @param str
     */
    public static void writeFile(File file, String str)
    {
        try
        {
            if(!file.exists())
                file.createNewFile();
            FileOutputStream out = new FileOutputStream(file,true); //true表示追加
            StringBuffer sb = new StringBuffer();
            sb.append(str + "\r\n");
            out.write(sb.toString().getBytes("utf-8"));//
            out.close();
        }
        catch(IOException ex)
        {
            System.out.println(ex.getStackTrace());
        }
    }

    /**
     * 写入文件,末尾自动添加\r\n
     * @param file
     * @param str
     */
    public static void writeFile(File file, String str, boolean is_append, String encode)
    {
        try
        {
            if(!file.exists())
                file.createNewFile();
            FileOutputStream out = new FileOutputStream(file, is_append); //true表示追加
            StringBuffer sb = new StringBuffer();
            sb.append(str + "\r\n");
            out.write(sb.toString().getBytes(encode));//
            out.close();
        }
        catch(IOException ex)
        {
            System.out.println(ex.getStackTrace());
        }
    }
    /**
     * 整个文件以string放回，添加\r\n换行
     * @param file
     * @return
     */
    public static String readFileByString(File file)
    {
        StringBuffer sb=new StringBuffer();
        String tempstr=null;
        try {
            if(!file.exists())
                throw new FileNotFoundException();
            FileInputStream fis=new FileInputStream(file);
            BufferedReader br=new BufferedReader(new InputStreamReader(fis, "utf-8"));
            while((tempstr=br.readLine())!=null) {
                sb.append(tempstr + "\r\n");
            }
        } catch(IOException ex) {
            ex.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 加入编码
     * 整个文件以string放回，添加\r\n换行
     * @param file
     * @return
     */
    public static String readFileByStringAndEncode(File file, String encode)
    {
        StringBuffer sb=new StringBuffer();
        String tempstr=null;
        try {
            if(!file.exists())
                throw new FileNotFoundException();
            FileInputStream fis=new FileInputStream(file);
            BufferedReader br=new BufferedReader(new InputStreamReader(fis, encode));
            while((tempstr=br.readLine())!=null) {
                sb.append(tempstr + "\r\n");
            }
        } catch(IOException ex) {
            System.out.println(ex.getStackTrace());
        }

        return sb.toString();
    }

    /**
     * 按行读取文件，以list<String>的形式返回
     * @param file
     * @return
     */
    public static List<String> readFileByLine(File file) {
        List<String> lines = new ArrayList<String>();
        String tempstr = null;
        try {
            if(!file.exists()) {
                throw new FileNotFoundException();
            }
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
            while((tempstr = br.readLine()) != null) {
                lines.add(tempstr.toString());
            }
        } catch(IOException ex) {
            System.out.println(ex.getStackTrace());
        }
        return lines;
    }



    /**
     * 创建目录
     * @param dir_path
     */
    public static void mkDir(String dir_path) {
        File myFolderPath = new File(dir_path);
        try {
            if (!myFolderPath.exists()) {
                myFolderPath.mkdir();
            }
        } catch (Exception e) {
            log.error("新建目录操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 创建文件
     * @param file_path
     */
    public static File createNewFile(String file_path) {
        parentIsExists(new File(file_path));
        File myFilePath = new File(file_path);
        try {
            if (!myFilePath.exists()) {
                myFilePath.createNewFile();
            }
            return new File(file_path);
        }
        catch (Exception e) {
            log.error("新建文件操作出错");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 递归删除文件或者目录
     * @param file_path
     */
    public static void deleteEveryThing(String file_path) {
        try{
            File file=new File(file_path);
            if(!file.exists()){
                return ;
            }
            if(file.isFile()){
                file.delete();
            }else{
                File[] files = file.listFiles();
                for(int i=0;i<files.length;i++){
                    String root=files[i].getAbsolutePath();//得到子文件或文件夹的绝对路径
                    deleteEveryThing(root);
                }
                file.delete();
            }
        } catch(Exception e) {
            log.error("删除文件失败");
        }
    }


    /**
     * 得到一个文件夹下所有文件
     * @param fold_path  String  文件路径
     * @return
     */
    public static List<String> getAllFileNameInFold(String fold_path) {
        List<String> file_paths = new ArrayList<String>();

        LinkedList<String> folderList = new LinkedList<String>();
        folderList.add(fold_path);
        while (folderList.size() > 0) {
            File file = new File(folderList.peekLast());
            folderList.removeLast();
            File[] files = file.listFiles();
            ArrayList<File> fileList = new ArrayList<File>();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    folderList.add(files[i].getPath());
                } else {
                    fileList.add(files[i]);
                }
            }
            for (File f : fileList) {
                file_paths.add(f.getAbsoluteFile().getPath());
            }
        }
        return file_paths;
    }

    /**
     * 判断目标文件所在的目录是否存在
     * @param file
     * @return
     */
    public static void parentIsExists(File file){
        //判断目标文件所在的目录是否存在
        if(!file.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录
//            System.out.println("目标文件所在目录不存在，准备创建它！");
            if(!file.getParentFile().mkdirs()) {
                System.err.println("创建目标文件所在目录失败！");
            }
        }
    }


    /**
     * 获得文件后缀
     * @param file
     * @return
     */
    public static String  getPostfix(File file){
        String[] strs=file.getName().split("\\.");
        return strs[strs.length-1].toLowerCase();
    }

    /**
     * 获得文件后缀
     * @param file
     * @return
     */
    public static String  getPostfix(String file){
        String[] strs=file.split("\\.");
        return strs[strs.length-1].toLowerCase();
    }

    /**
     * 修改文件后缀
     * @param file
     * @param postfix
     * @return
     */
    public static File fileChangePostfix(File file ,String postfix){
        File newFile=new File(file.getAbsolutePath().substring(0,file.getAbsolutePath().lastIndexOf(".")+1)+postfix);
        if(file.exists()){
            file.delete();
        }
        return newFile;
    }

    /**
     * 遍历目录下面的所有文件
     * @param file
     * @param depth
     * @return
     */
    public static List<File> listFiles(File file,int depth){
        List<File> res=new ArrayList<>();
        File[] files=file.listFiles();
        for(File f:files){
            if(f.isDirectory()){
                res.addAll(listFiles(f,depth+1));
            }else{
                res.add(f);
            }
        }
        return res;
    }

    /**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    //写文件时注意编码要统一，不然乱码
    public static String reader(File file){
        StringBuilder result = new StringBuilder();
        String fileContent = "";
        try
        {
            if(file.isFile()&&file.exists())
            {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file),"utf8");
                BufferedReader reader=new BufferedReader(read);
                String line;
                //使用readLine方法，一次读一行
                while ((line = reader.readLine()) != null)
                {
                    //	result.append(System.lineSeparator()+line);
                    fileContent += line;
                }
                read.close();
            }
        } catch (Exception e)  {
            e.printStackTrace();
        }
//		try {
//			fileContent=new String(fileContent.getBytes("gbk"),"UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
        //	return fileContent;
        return  fileContent;
    }

    /**
     * 文件复制
     * @param source
     * @param dest
     * @throws IOException
     */
    public static void copyFileUsingFileChannels(File source, File dest) throws IOException {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }
    }


    public static void main(String[] args) {
        String fileName = System.getProperty("user.dir")+File.separator+"text.txt";
        System.out.println(fileName);
//        readFileByBytes(fileName);
//        readFileByChars(fileName);
//        String content=readFileByLines(fileName);
        String content=null;
        content=reader(new File(fileName));

        System.out.println(content);

        long start =System.currentTimeMillis();
        System.out.println(content.contains("名字和电话号码"));
        long end=System.currentTimeMillis();
        System.out.println(end-start);
    }




}
